<template>
  <div class="event-report">
    <header-bar :title="'事件上报'">
      <template v-slot:backBtn>
        <i @click="closeWebView" class="iconarrow_back"></i>
      </template>
    </header-bar>
    <div class="report-data">
      <cube-scroll>
        <div class="handle-opinion">
          <p class="flex-line"><span class="name-space">事件描述<i class="require"></i></span></p>
          <cube-textarea v-model="submitData.eventDesc" placeholder="请输入事件描述"></cube-textarea>
        </div>
        <ul class="handle-list">
          <li class="border-line flex-line event-time border-line-top">
            <span class="name-space">事件来源<i class="require"></i></span>
            <cube-input v-model="submitData.eventSourceName" :disabled="true" class="no-border"></cube-input>
            <!-- <picker-common :alias="{value: 'codeValue',text: 'codeName'}" :selectData.sync="eventSource" :pickerList="sourceList" :title="'事件来源'" :selectVal="eventSource"></picker-common> -->
          </li>
          <li class="border-line flex-line event-time">
            <span class="name-space">事件时间<i class="require"></i></span>
            <div @click="openTimePicker" class="event-time-select">
              <cube-input v-model="submitData.eventTime" placeholder="日期选择" :disabled="true"></cube-input>
              <i class="iconarrow_right"></i>
            </div>
          </li>
          <li class="border-line flex-line">
            <span class="name-space">事件大类<i class="require"></i></span>
            <picker-common :alias="{value: 'code',text: 'activeName'}" :selectData.sync="bigType" :pickerList="bigTypeList" :title="'事件大类'" :selectVal="bigType"></picker-common>
          </li>
          <li class="border-line flex-line">
            <span class="name-space">事件小类<i class="require"></i></span>
            <picker-common :updateFunc="updateSmallList" :alias="{value: 'code',text: 'activeName'}" :selectData.sync="smallType" :pickerList="smallTypeList" :title="'事件小类'" :selectVal="smallType"></picker-common>
          </li>
          <li class="handle-opinion border-line">
            <p class="flex-line">
              <span>事件地址<i class="require"></i></span>
              <i class="iconlocation" @click="handleAddress"></i>
            </p>
            <cube-textarea v-model="submitData.eventAddress" placeholder="请输入详细地址"></cube-textarea>
          </li>
          <li class="border-line flex-line">
            <span class="name-space">所属区县<i class="require"></i></span>
            <picker-common :alias="{value: 'code',text: 'name'}" :selectData.sync="eventArea" :pickerList="areaList" :title="'所属区域'" :selectVal="eventArea"></picker-common>
          </li>
          <li class="border-line flex-line">
            <span class="name-space">所属街道</span>
            <picker-common :updateFunc="updateStreetList" :alias="{value: 'code',text: 'name'}" :selectData.sync="eventStreet" :pickerList="streetList" :title="'所属社区'" :selectVal="eventStreet"></picker-common>
          </li>
          <li class="border-line flex-line">
            <span class="name-space">所属道路</span>
            <picker-common :updateFunc="updateRoadList" :alias="{value: 'road_no',text: 'road_name'}" :selectData.sync="eventRoad" :pickerList="roadList" :title="'所属街道'" :selectVal="eventRoad"></picker-common>
          </li>
          <li class="border-line flex-line">
            <span class="name-space">事件等级</span>
            <picker-common :selectData.sync="eventLevel" :pickerList="urgentList" :title="'事件等级'" :selectVal="eventLevel"></picker-common>
          </li>
          <li class="border-line flex-line handle-switch">
            <span class="name-space">定时巡查</span>
            <cube-switch v-model="submitData.regularPatrol"></cube-switch>
          </li>
          <li class="image-upload event-img border-line">
            <p><span>事件图片<i class="require"></i></span><span>(最多上传5张)</span></p>
            <cube-upload 
              ref="upload"
              :auto="false"
              :max="5" 
              v-model="uploadImgs" 
              :simultaneous-uploads="1"
              ></cube-upload>
          </li>
          <li class="handle-opinion">
            <p>备注</p>
            <cube-textarea v-keyboardfocus v-model="submitData.eventRemark" placeholder="请输入备注消息"></cube-textarea>
          </li>
        </ul>
      </cube-scroll>
    </div>
    <div class="btn-groups">
      <div @click="handleSubmit" class="btn">
        上 报
      </div>
      <div @click="handleDeal" class="btn">
        处 理
      </div>
    </div>

    <handle-content ref="handle" :baseData="baseData" @handleChange="handleChangePage" @report="handleBeforeReport" class="handle-container" v-if="handleShow"></handle-content>
  </div>
</template>

<script>
import { format, valiData } from '@/common/js/utils'
import { closeWebView } from '@/common/js/android'
import { uploadFiles } from '@/api/upload.js'
import { searchParentEventType, searchChildEventType, listRoad, getGroupnoToAreaCode } from '@/api/maintain.js';
import { findArea, insertEvent } from '@/api/eventAPI.js'
export default {
  components: {
    'header-bar': () => import('@/components/header-bar/header-bar'),
    'picker-common': () => import('@/components/picker-common/picker-common'),
    'handle-content': () => import('@/views/task-info/handle-content')
  },
  data() {
    return {
      uploadImgs: [],
      
      bigType: {id: '', text: ''},
      smallType: {id: '', text: ''},
      eventSource: {id: '', text: ''},
      eventArea: {id: '', text: ''},
      eventStreet: {id: '', text: ''},
      eventRoad: {id: '', text: ''},
      eventLevel: {id: '3', text: '一般'},
      
      bigTypeList: [],
      smallTypeList: [],
      sourceList: [],
      areaList: [],
      streetList: [],
      roadList: [],
      urgentList: [
        { text: '一般', value: '3' },
        { text: '紧急', value: '2' },
        { text: '特急', value: '1' },
      ],

      submitData: {
        assigner: "",
        enclosureUrl: "",
        eventAddress: "", //事件地址
        eventArea: "",
        eventAreaCode: "", // 区县
        eventDesc: "", // 事件描述
        eventId: null,
        eventLargeType: "",
        eventLargeTypeCode: "", // 事件大类
        eventLatitude: '',
        eventLevel: null, // 事件等级
        eventLongitude: '',
        eventReportId: "",
        eventReportName: "",
        eventReportPhone: "",
        eventRoad: "", // 道路
        eventSmallType: "",
        eventSmallTypeCode: "", // 事件小类
        eventSource: '5', // 事件来源
        eventSourceName: "巡查发现",
        eventStreet: "",
        eventStreetCode: "", // 街道
        eventTime: format(new Date(), 'yyyy-MM-dd hh:mm:ss'), // 事件时间
        eventRemark: "", // 备注
        personEnclosureUrl: "", // 文件地址，逗号隔开
        regularPatrol: false, // 是否定时巡查
        userId: "",
        userName: "",
        userOrgId: "",
        userOrgName: ""
      },
      dateTimePicker: null,
      baseData: {},
      handleShow: false, // 显示处理操作
      param: {} // 保存上报参数
    }
  },
  watch: {
    bigType(n) {
      this.submitData.eventLargeTypeCode = n.id
      this.submitData.eventLargeType = n.text
      this.smallType = {id: '', text: ''}
      this.submitData.eventSmallTypeCode = ''
      this.submitData.eventSmallType = ''
      if(n.id) {
        let code = this.bigTypeList.filter(item => item.code == n.id)[0].code
        this.resetSmallData('smallType', code)
      }
    },
    smallType(n) {
      this.submitData.eventSmallTypeCode = n.id
      this.submitData.eventSmallType = n.text
    },
    // eventSource(n) {
    //   this.submitData.eventSource = n.id
    //   this.submitData.eventSourceName = n.text
    // },
    eventArea(n) {
      this.submitData.eventAreaCode = n.id
      this.submitData.eventArea = n.text
      this.eventStreet = {id: '', text: ''}
      this.submitData.eventStreetCode = ''
      this.submitData.eventStreet = ''
      this.resetSmallData('street', n.id)
    },
    eventStreet(n) {
      this.submitData.eventStreetCode = n.id
      this.submitData.eventStreet = n.text
      this.eventRoad = {id: '', text: ''}
      this.submitData.eventRoad = ''
      if(n.id) {
        this.resetSmallData('road', n.id)
      }
    },
    eventRoad(n) {
      this.submitData.eventRoad = n.text
    },
    eventLevel(n) {
      this.submitData.eventLevel = n.id
    }
  },
  computed: {
    from() {
      return this.$route.query.from
    },
    userInfo() {
      return JSON.parse(window.localStorage.getItem('user'))
    }
  },
  created(){
    this.getSelectList()
    // this.eventSource = {id: '5', text: '巡查发现'}
  },
  methods: {
    // 获取当前登录人的区域代码
    getGroupnoToArea() {
      getGroupnoToAreaCode('00020B0G').then(res => {
        if(res.code == 0) {
          let eventAreaCode = res.data.areaId
          let eventArea = this.areaList.filter(
            item => item.code == res.data.areaId
          )[0].name;
          this.eventArea = {id: eventAreaCode, text: eventArea}
        }
      })
    },
    async getSelectList(){
      try {
        let data = await Promise.all([
          // searchDictList("EVENT_SOURCE"),
          searchParentEventType(),  //  获取大类
          findArea(),   //  获取区局
        ])
        this.bigTypeList = data[0].data
        this.areaList = data[1].data
        // this.sourceList = data[0].data

        this.getGroupnoToArea()
      } catch (error) {
        console.log(error);
      }
    },
    updateSmallList(picker) {
      picker && picker.$updateProps({
        data: [this.smallTypeList],
        selectedIndex: [0]
      })
    },
    updateStreetList(picker) {
      picker && picker.$updateProps({
        data: [this.streetList],
        selectedIndex: [0]
      })
    },
    updateRoadList(picker) {
      picker && picker.$updateProps({
        data: [this.roadList],
        selectedIndex: [0]
      })
    },
    // 点击选中地图
    handleAddress() {
      let obj = {}
      if(this.submitData.eventLatitude) {
        obj = { 
          lat: this.submitData.eventLatitude, 
          lon: this.submitData.eventLongitude, 
          address: this.submitData.eventAddress
        }
      }
      let _this = this
      window.WebViewJavascriptBridge.callHandler(
        'markPosition'
        , obj
        , function (responseData) {
          console.log(responseData);
          let res = JSON.parse(responseData)
          if(res.area) {
            _this.submitData.eventLatitude = res.lat
            _this.submitData.eventLongitude = res.lon
            _this.submitData.eventAddress = res.address
            // 选择地址后填充区域和地址
            const param = _this.areaList.find(item => item.name == res.area)
            _this.eventArea = {id: param.code, text: param.name}
            
            findArea(param.code).then(res2 => {
              if(res2.code === 0) {
                _this.streetList = res2.data
                const param2 = _this.streetList.find(item => item.name == res.street)
                _this.eventStreet = {id: param2.code, text: param2.name}
              }
            })
          }
        }
      );
    },

    closeWebView(){
      this.$router.go(-1)
      closeWebView()
    },
    openTimePicker(){
      if (!this.dateTimePicker) {
        this.dateTimePicker = this.$createDatePicker({
          title: '日期选择',
          min: new Date(2008, 7, 8, 8, 0, 0),
          max: new Date(),
          value: new Date(),
          columnCount: 6,
          onSelect: this.selectHandle
        })
      }
      this.dateTimePicker.show()
    },
    selectHandle(time){
      this.submitData.eventTime = format(time,'yyyy-MM-dd hh:mm:ss')
    },
    async resetSmallData(type, vlaue){
      let promise = ''
      if(type == 'smallType') {
        promise = searchChildEventType(vlaue)
      } else if (type == 'street') {
        promise = findArea(vlaue)
      } else {
        let data = {
          code: this.submitData.eventAreaCode,
          street_code: this.submitData.eventStreetCode
        }
        promise = listRoad(data)
      }
      
      let {data} = await promise;
      type==='street'?(this.streetList = data):type==='road'?(this.roadList=data):(this.smallTypeList=data)
    },
    // 录入 -- 处理
    async handleDeal() {
      let valid = await this.valid()
      if(!valid) return;
      this.handleShow = true
    },
    handleChangePage(type = 0) {
      this.handleShow = false
      // 处理成功需要重置表单
      if(type) {
        this.reset()
      }
    },
    async handleBeforeReport() {
      let res = await this.report(this.param)
      if(res.code==0) {
        this.$refs.handle.handleSubmit(res.data)
      } else {
        this.$refs.handle.handleSubmit(false)
      }
    },
    _canconfirm(){
      return this.$refs.upload.files.every((item)=>{
        return item.status === 'success'
      })
    },
    async uploadFiles() {
      const res = await uploadFiles(this.uploadImgs); // 上传文件到 OSS
      this.submitData.enclosureUrl = JSON.stringify([...res])
    },
    async valid() {
      await this.uploadFiles()
      this.param = {
        ...this.submitData,
        eventReportId: this.userInfo.userId,
        eventReportName: this.userInfo.userName,
        eventReportPhone: this.userInfo.telephone,
        eventLevel: this.eventLevel.id,
        userId: this.userInfo.userId,
        userName: this.userInfo.userName,
        userOrgId: this.userInfo.groupId,
        userOrgName: this.userInfo.groupName,
        assigner: this.userInfo.orgLevel
      };
      if(!valiData.call(this,{
        eventDesc: {cond: "String($$).length>0", pro: '请输入事件描述'},
        eventAddress: {cond: "String($$).length>0", pro: '请输入事件地址'},
        // eventSource: {cond: "/\\d+/.test($$)", pro: '请选择事件来源'},
        eventLargeTypeCode: {cond: "/\\d+/.test($$)", pro: '请选择事件大类'},
        eventSmallTypeCode: {cond: "/\\d+/.test($$)", pro: '请选择事件小类'},
        eventAreaCode: {cond: "/\\d+/.test($$)", pro: '请选择区县'},
        enclosureUrl: {cond: "String($$).length>3", pro: '请选择上报图片'}
      }, this.param)) {
        return false
      } else return true
    },
    async handleSubmit(){
      let valid = await this.valid()
      if(!valid) return;
      this.$createDialog({
        type: 'confirm',
        icon: 'cubeic-alert',
        title: '确认提交？',
        confirmBtn: {
          text: '确定'
        },
        cancelBtn: {
          text: '取消'
        },
        onConfirm: async () => {
          const toast = this.$createToast({
            time: 0,
            mask: true,
            txt: '提交中....'
          })
          toast.show()

          let res = await this.report()
          toast.hide()
          if(res.code == 0){
            this.$createToast({
              txt: '上报成功',
              type: 'correct'
            }).show()
            this.reset();
            // setTimeout(()=>{
            //   closeWebView()
            // },500)
          }else{
            this.$createToast({
              txt: '上报失败',
              type: 'error'
            }).show()
          }
        }
      }).show();
    },
    async report() {
      try {        
        let res = await insertEvent(this.param)
        return res
      } catch(err) {
        console.log(err);
        return false
      }
    },
    reset() {
      this.bigType = {id: '', text: ''}
      this.smallType = {id: '', text: ''}
      // this.eventSource = {id: '', text: ''}
      this.eventArea = {id: this.userInfo.parentGroupId, text: this.userInfo.parentGroupName}
      this.eventStreet = {id: '', text: ''}
      this.eventRoad = {id: '', text: ''}
      this.eventLevel = {id: '3', text: '一般'}
      this.smallTypeList = []
      this.uploadImgs = []
      this.streetList =  []
      this.roadList =  []
      this.submitData = {
        assigner: "",
        enclosureUrl: "",
        eventAddress: "", //事件地址
        eventArea: "",
        eventAreaCode: "", // 区县
        eventDesc: "", // 事件描述
        eventId: null,
        eventLargeType: "",
        eventLargeTypeCode: "", // 事件大类
        eventLatitude: '',
        eventLevel: null, // 事件等级
        eventLongitude: '',
        eventReportId: "",
        eventReportName: "",
        eventReportPhone: "",
        eventRoad: "", // 道路
        eventSmallType: "",
        eventSmallTypeCode: "", // 事件小类
        eventSource: '5', // 事件来源
        eventSourceName: "巡查发现",
        eventStreet: "",
        eventStreetCode: "", // 街道
        eventTime: format(new Date(), 'yyyy-MM-dd hh:mm:ss'), // 事件时间
        eventRemark: "", // 备注
        personEnclosureUrl: "", // 文件地址，逗号隔开
        regularPatrol: false, // 是否定时巡查
        userId: "",
        userName: "",
        userOrgId: "",
        userOrgName: ""
      }
      this.getGroupnoToArea()
    },
    showToast(msg){
      this.$createToast({
        txt: msg,
        type: 'error'
      }).show()
    }
  }
}
</script>

<style lang="stylus">
@import '../../assets/css/image.styl'
.event-report{
  background:rgba(245,245,245,1);
  width:100%;
  height: 100%;
  .report-data{
    height: calc(100vh - 110px);
    .handle-opinion{
      width: 100%;
      height: 110px;
      background:rgba(255,255,255,1);
      p{
        height: 30px;
        display: flex;
        flex-flow: row nowrap;
        align-items flex-end;
        font-size:14px;
        font-family:PingFangSC-Regular;
        font-weight:400;
        color:rgba(51,51,51,1);
        text-indent: 10px;
        position relative;
        .iconlocation{
          color: rgba(248, 139, 67, 1);
          font-size: 20px;
          position absolute;
          right: 12px;
          top: 7px;
        }
      }
      .cube-textarea-wrapper{
        font-size:14px;
        font-family:PingFangSC-Regular;
        font-weight:400;
        // color:rgba(153,153,153,1);
        height: 80px;
        .cube-textarea{
          font-size:14px;
          font-family:PingFangSC-Regular;
          font-weight:400;
          // color:rgba(153,153,153,1);
          padding-left 15px;
        }
        &::after{
          border: none;
        }
      }
    }
    .handle-list{
      background: #fff;
      .event-img{
        margin-top: 0;
      }
      .handle-switch{
        padding-right 7px
        height 44px
        .cube-switch{
          margin-right: 12px;
          .cube-switch-ui::before{
            background-color: rgba(221,221,221,1);
          }
        }
      }
      .road-name{
        height: 80px;
        p{
          height: 40px;
        }
        .cube-input{
          &::after{
            border: none;
          }
        }
      }
      .event-time{
        height 44px
        .event-time-select{
          display: flex;
          flex-flow: row nowrap;
          align-items center;
          width 200px
          .iconarrow_right{
            color: #aaa;
            margin-right 8px;  
          }
          .cube-input{
            &::after{
              border: none;
            }
            input{
              text-align: right
              width 167px
            }
          }
        }  
      }
    }
  }
  
  .require{
    position: relative
    &:before{
      position: absolute
      left: -12px;
      top: 5px;
      content: '*';
      color: #f00;
    }
  }
}

.btn-groups{
    position fixed 
    bottom 0
    left 0
    z-index 100
    background-color #f5f5f5
    padding 12px 0
    width: 100%;
    height:41px;
    display: flex;
    justify-content: space-around;
    .btn{
      width: 46%;
      height: 100%;
      background:rgba(4,48,102,1);
      border-radius:4px;
      text-align center;
      line-height 41px;
      font-size:15px;
      font-family:PingFangSC-Regular;
      font-weight:400;
      color:rgba(255,255,255,1);
    }
  }

.handle-container {
  position absolute
  top 0
  left 0  
  background-color #fff
  width 100%
  z-index 100
}
.no-border {
  padding-right 12px
  input {
    text-align right
  }
  &::after {
    border none
  }
}
</style>
